package studiodiva.portfolio.client.model.titles;

import com.google.gwt.core.client.GWT;

import java.util.Iterator;

import studiodiva.portfolio.client.lib.collections.LinkedHashMap;
import studiodiva.portfolio.client.lib.collections.LinkedMap;
import studiodiva.portfolio.client.lib.lang.Base;
import studiodiva.portfolio.client.model.HasApplication;
import studiodiva.portfolio.client.model.titles.Titles.TitleType;
import studiodiva.portfolio.client.resources.pages.PagesData;
import studiodiva.portfolio.client.resources.pages.PagesStrings;

public class TitleImpl extends Base implements Title {

  protected static final PagesData data = GWT.create(PagesData.class);
  protected static final PagesStrings strings = GWT.create(PagesStrings.class);
  private int currentIndex = 0;
  private final LinkedMap<String, Page> pages = new LinkedHashMap<String, Page>();
  private final TitleType type;

  public TitleImpl(HasApplication parent, TitleType type) {
    this.type = type;
    initialize(parent);
  }

  public Page getPage() {
    return getPage(currentIndex);
  }

  public int getCurrentIndex() {
    return currentIndex;
  }

  public Page getPage(int index) {
    return pages.getValue(index);
  }

  public int getPageCount() {
    return pages.size();
  }

  public TitleType getType() {
    return type;
  }

  public Iterator<Page> iterator() {
    return pages.values().iterator();
  }

  public void showPage(int index) {
    if (currentIndex == index) return;
    currentIndex = index;
    fireEvent(ON_PAGE_CHANGE, getPage());
  }

  public void showPage(String key) {
    showPage(pages.indexOf(key));
  }

  protected void add(Page page) {
    pages.put(page.getId(), page);
  }
}
